/**
 * Project Name:fire-industry-DM-center
 * File Name:UserDetailsServiceImpl.java
 * Package Name:com.firestone.service.user.impl
 * Date:2018年3月22日下午1:47:07
 *
*/

package com.firestone.service.user.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.firestone.bean.dto.user.User;
import com.firestone.bean.entity.mysql.primary.ImCenterManager;
import com.firestone.service.center.IImCenterManagerService;
import com.firestone.service.center.IImCenterResourceService;

/**
 * @Description: TODO(权限认证业务实现类)
 * @author CAIYJ
 * @date 2018年3月22日 下午1:47:07
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LogManager
            .getLogger(UserDetailsServiceImpl.class);

    private IImCenterManagerService imCenterManagerService;

    private IImCenterResourceService imResourceService;

    /**
     * 通过构造器注入UserRepository
     * 
     * @param userRepository
     */
    public UserDetailsServiceImpl(
            IImCenterManagerService imCenterManagerService,
            IImCenterResourceService imResourceService) {
        this.imCenterManagerService = imCenterManagerService;
        this.imResourceService = imResourceService;
    }

    @Override
    public UserDetails loadUserByUsername(String name)
            throws UsernameNotFoundException {
        
        EntityWrapper<ImCenterManager> ew = new EntityWrapper<ImCenterManager>();
        ew.setEntity(new ImCenterManager());
        ew.where("username = {0}", name).and("is_delete = {0}", 1);
        ImCenterManager manager = imCenterManagerService.selectOne(ew);
        if (null == manager) {
            throw new UsernameNotFoundException(name);
        }
        
        User user = new User(manager.getId(), manager.getUsername(),
                manager.getPassword());
        
        List<Object> urls = null;
        try {
            urls = imResourceService.listPermissionUrl(user.getId());
        } catch (Exception e) {
            logger.error("获取权限异常", e);
        }
        if (null != urls && urls.size() > 0) {
            List<GrantedAuthorityImpl> list = new ArrayList<>();
            for (Object url : urls) {
                GrantedAuthorityImpl grantedAuthorityImpl = new GrantedAuthorityImpl(
                        (String) url);
                list.add(grantedAuthorityImpl);
            }
            user.setAuthorities(list);
        }
        return user;
    }

}
